<script setup lang="ts">
import { ref, onMounted } from "vue";
import { getWorkSheetDetail, replyWorkSheet,deleteWorkSheet } from "@/api/worksheet";
import { useRoute, useRouter } from "vue-router";
import { uploadFile } from '@/api/message';
import { message } from '@/utils/message';
import { mainUrl } from '@/api/utils';
const route = useRoute();
const router = useRouter();
const title=ref('')
onMounted(async () => {
  //获取工单内容
  let res = await getWorkSheetDetail(route.query.sheet_id);
  console.log(res.data.data, "这是工单内容");
  let data = res.data.data.content;
  title.value = res.data.data.title;
  messages.value = JSON.parse(data);
  messages.value = messages.value.map((item) => {
    if (item.content.includes('@@@')) {
      let parts = item.content.split("@@@") ;
      let part1 = parts[0];
      let part2 = parts[1];
      item.content = part1;
      const aid = part2;
      return { ...item,aid };
    } else {
      return item;
    }
  });
  console.log('信息数据 ',messages.value)
});
const messages = ref([{ type: 1, content: "我遇到问题了" }]);
let newMessage = ref("");
const sendMessage = async () => {
  if (aid.value != null) {
    newMessage.value += `@@@${aid.value}`
  }
  if (newMessage.value.trim()) {
    let res = await replyWorkSheet({
      sheet_id: route.query.sheet_id,
      content:newMessage.value
    });
    console.log("回复结果", res);
    newMessage.value=''
    if (res.data.code == 200) {
      let res = await getWorkSheetDetail(route.query.sheet_id);
      let data = res.data.data.content;
      messages.value = JSON.parse(data);
    }
  }
};
//删除工单
const confirmEvent = async() => {
  let res = await deleteWorkSheet({
    sheet_id: route.query.sheet_id
  });
  console.log('工单删除结果',res)
  if(res.data.success){
    router.push({
      path: "/workSheet/workSheet"
    });
  }

}
const cancelEvent = () => {
  console.log('取消!')
}
//上传附件
const aid=ref(null)
const selectedFileName = ref(null);
const onFileSelected = (event) => {
  const file = event.target.files[0];
  if (file) {
    selectedFileName.value = file.name; // 显示文件名
    uploadFile({ file: file}).then((res) => {
      console.log('上传文件', res.data.data.attachment_id)
      if (res.data.code == 200) {
        message('上传成功', { type: 'success' });
        aid.value = res.data.data.attachment_id
      }
    })
  } else {
    selectedFileName.value = null; // 如果用户取消选择，清空文件名
  }
}
</script>

<template>
  <div>

    <el-card class="chat-container">
      <div style="
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px;
        ">
        <h3>{{ title }}</h3>
        <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled" title="您确认删除吗？删除后操作不可逆！"
          @confirm="confirmEvent" @cancel="cancelEvent">
          <template #reference>
            <el-button>
              删除工单</el-button>
          </template>
        </el-popconfirm>
      </div>



      <div class="chat-messages">
        <el-card v-for="message in messages" class="message">
          <div class="message-content">{{ message.content }}</div>
          <div v-if="message.aid">
            <a style="color: #409EFF;" :href="`${mainUrl}/v1/attachment/get_attachment?aid=${message.aid}`"
              download>下载附件</a>
          </div>
          <div class="message-author" :style="'color:' + (message.type == 1 ? '#409effcf' : 'green')">
            {{ message.type == 1 ? "管理员" : "用户" }} <br />
            {{ message.timestamp }}
          </div>
        </el-card>
      </div>

      <el-input v-model="newMessage" style="width: 100%; padding: 10px" :rows="2" type="textarea" placeholder="请输入" />
      <div style="
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px;
        ">
        <el-button class="btn" @click="$refs.fileInput.click()">上传附件</el-button>
        <input type="file" ref="fileInput" @change="onFileSelected" style="display:none" />
        <span v-if="selectedFileName" class="file-name">{{ selectedFileName }}</span>
        <el-button type="primary" @click="sendMessage()">回复</el-button>


      </div>



    </el-card>
  </div>
</template>

<style scoped>
.chat-container {
  width: 100%;
  padding: 20px;
  margin: 0 auto;
  margin-top: 20px;
  background: white;
  border-radius: 5px;
}

.chat-messages {
  padding: 10px;
}

.message {
  padding: 10px;
  margin-bottom: 15px;
  background: #f3f3f3;
  border-radius: 5px;
}

.message-content {
  margin-bottom: 5px;
}

.message-author {
  font-size: 12px;
  text-align: right;
}
</style>
